/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hanze.shoestring.dao.impl;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import nl.hanze.shoestring.dao.LandDAO;
import nl.hanze.shoestring.domain.Continent;
import nl.hanze.shoestring.domain.Continent_;
import nl.hanze.shoestring.domain.Land;
import nl.hanze.shoestring.domain.Land_;

/**
 *
 * @author alex
 */
public class LandDAOImpl extends BaseDAOImpl<Land> implements LandDAO {

    public LandDAOImpl() {
    }

    @Override
    public List<Land> find(String name) {
        boolean hasName = name != null && name.length() > 0;
        if (!hasName) {
            return getAll();
        }

        List<Predicate> prList = new ArrayList<>();

        open();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Land> query = cb.createQuery(Land.class);
        Root<Land> land = query.from(Land.class);
        Join<Land, Continent> continent = land.join(Land_.continentId);

        if (hasName) {
            prList.add(cb.or(cb.like(continent.get(Continent_.naam), name + "%"),cb.like(land.get(Land_.naam), name + "%")));
        }

        //Zet beperkingen om naar lijst
        Predicate[] p = new Predicate[prList.size()];
        prList.toArray(p);

        query.where(p);

        TypedQuery<Land> typedQuery = em.createQuery(query);
        return typedQuery.getResultList();
    }
}
